<template>
  <div class="container">
    <div>
      <div>
        <el-form ref="dataForm" :model="record" :rules="recordRules" label-position="top" size="small"  label-width="110px">
          <el-row :gutter="20">
            <el-col :span="20">
              <el-form-item label="授权人" prop="formUserName">
                <el-input v-model="record.formUserName" placeholder="请输入授权人" class="myWidth" :readonly="true">
                  <el-button slot="append" icon="el-icon-search" @click="toSelectFormUser">选择</el-button>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="被授权人" prop="toUserName">
                <el-input v-model="record.toUserName" placeholder="请输入被授权人" class="myWidth" :readonly="true">
                  <el-button slot="append" icon="el-icon-search" @click="toSelectUser">选择</el-button>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <el-form-item label="是否所有业务" prop="isAllBusi">
                <el-select v-model="record.isAllBusi" placeholder="请选择是否所有业务" :clearable="true" class="myWidth">
                  <el-option v-for="item in trueOrFalseOptions" :key="item.value"
                             :label="item.label":value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="授权开始时间" prop="beginTime">
                <el-date-picker v-model="record.beginTime" size="small" type="datetime" :editable="false" class="myWidth"
                                placeholder="请选择授权开始时间" default-time="00:00:00" value-format="yyyyMMddHHmmss">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <el-form-item label="授权结束时间" prop="endTime">
                <el-date-picker v-model="record.endTime" size="small" type="datetime" :editable="false" class="myWidth"
                                placeholder="请选择授权结束时间" default-time="23:59:59" value-format="yyyyMMddHHmmss">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="是否所有公司单据" prop="isAllCorp">
                <el-select v-model="record.isAllCorp" placeholder="请选是否所有公司单据" :clearable="true" class="myWidth">
                  <el-option v-for="item in trueOrFalseOptions" :key="item.value"
                    :label="item.label":value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <el-form-item label="授权单据所在公司" prop="busiCorpName">
                <el-input v-model="record.busiCorpName" placeholder="请输入授权单据所在公司" :clearable="true" class="myWidth" :readonly="true">
                  <el-button slot="append" icon="el-icon-search" @click="toSelectCorp">选择</el-button>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" v-if="record.isAllBusi !=='1'">
            <el-col>
              <el-form-item label="授权业务类型：" prop="busiTypeList">
                <el-checkbox-group v-model="checkBusiTypeList">
                  <el-col :span="6" v-for="item in allBusiTypeList" :key="item.busiTypeId" style="padding: 3px 0px">
                    <el-checkbox :label="item.busiTypeId">{{item.busiTypeName}}</el-checkbox>
                  </el-col>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="menu-navbar">
        <el-button size="small" type="success" icon="el-icon-close" @click="createSave('dataForm', 'save')">保存</el-button>
        <el-button size="small" type="info" icon="el-icon-close" @click="closeComponent()">关闭</el-button>
      </div>
    </div>
    <el-dialog title="授权人员选择" :visible.sync="selectFormUserDialog" width="60%" :close-on-click-modal="false" :destroy-on-close="true"
               v-if="selectFormUserDialog" top="30px" custom-class="myDialog" :append-to-body="true">
      <sys-user-select :multipleSelection="false" @closeComponent="closeSelectFormUser"></sys-user-select>
    </el-dialog>
    <el-dialog title="人员选择" :visible.sync="selectUserDialog" width="60%" :close-on-click-modal="false" :destroy-on-close="true"
               v-if="selectUserDialog" top="30px" custom-class="myDialog" :append-to-body="true">
      <sys-user-select :multipleSelection="false" @closeComponent="closeSelectUser"></sys-user-select>
    </el-dialog>
    <el-dialog title="公司选择" :visible.sync="selectCorpDialog" width="55%" :close-on-click-modal="false" :destroy-on-close="true"
               v-if="selectCorpDialog" top="30px" custom-class="myDialog" :append-to-body="true">
      <sys-corp-select :multipleSelection="false" @closeComponent="closeSelectCorp"></sys-corp-select>
    </el-dialog>
  </div>
</template>
<script>
// import { closeTab } from '@/utils/index'
import { wfBusiTypeSelect } from '@/api/workFlowManage/busiWorkFlowConfig'
import { queryRecord, insertRecordExt as insertRecord, updateRecordExt as updateRecord } from '@/api/workFlowManage/wfBusiAgent'
import { default as sysUserSelect } from '@/views/common/components/sysUserSelect'
import { default as sysCorpSelect } from '@/views/common/components/sysCorpSelect'

export default {
  name: 'wfBusiDemoDetail',
  data() {
    return {
      busiTypeId: 'wfBusiDemo',
      curUserId: this.$store.state.user.userid,
      curUserName: this.$store.state.user.name,
      curOrgId: this.$store.state.user.orgId,
      curCorpId: this.$store.state.user.corpId,
      trueOrFalseOptions: [
        {
          value: '1',
          label: '是'
        },
        {
          value: '0',
          label: '否'
        }
      ],
      record: {
        id: '',
        formUserId: '',
        formUserName: '',
        toUserId: '',
        toUserName: '',
        beginTime: '',
        endTime: '',
        isAllCorp: '',
        busiCorpId: '',
        busiCorpName: '',
        isAllBusi: '',
        status: '',
        busiTypeList: []
      },
      allBusiTypeList: [],
      allBusiTypeKeyValue: {},
      checkBusiTypeList: [],
      recordRules: {
        toUserName: [
          { message: '被授权人不能为空', required: true, trigger: 'change' }
        ],
        isAllBusi: [
          { message: '是否所有业务不能为空', required: true, trigger: 'change' }
        ],
        isAllCorp: [
          { message: '是否所有公司单据不能为空', required: true, trigger: 'change' }
        ],
        beginTime: [
          { message: '授权开始时间不能为空', required: true, trigger: 'blur' }
        ],
        endTime: [
          { message: '授权开始结束不能为空', required: true, trigger: 'blur' }
        ],
        busiCorpName: [
          { message: '授权单据所在公司不能为空', required: true, trigger: 'change' },
          { message: '授权单据所在公司不能为空', required: true, trigger: 'blur' }
        ]
      },
      selectFormUserDialog: false,
      selectUserDialog: false,
      selectCorpDialog: false
    }
  },
  props: ['componentCustomProps'],
  components: {
    sysUserSelect,
    sysCorpSelect
  },
  created() {
    if (this.componentCustomProps) {
      this.currentComParams = this.componentCustomProps
    } else {
      this.currentComParams = this.$route.query
    }
    this.initPage()
  },
  watch: {
    componentCustomProps() { // 普通的watch监听通的watch监听
      this.initPage()
    },
    'record.isAllCorp': {
      handler: function() {
        // alert(this.record.isAllCorp)
        if (this.record.isAllCorp === '1') {
          this.recordRules.busiCorpName = []
          this.$refs['dataForm'].clearValidate('busiCorpName')
        } else {
          this.recordRules.busiCorpName = [
            { message: '授权单据所在公司不能为空', required: true, trigger: 'blur' }
          ]
        }
      }
    }
  },
  methods: {
    initPage() {
      this.getBusiTypeList()
      if (this.currentComParams.openType === 'edit') {
        this.record.id = this.currentComParams.busiId
        this.fetchData()
      }
    },
    getBusiTypeList() {
      let queryArgs = {
        condition: [
          {
            property: 'status', // 状态
            type: 'EQ',
            value: '0'
          },
          {
            property: 'isUseAgent', // 使用代理授权
            type: 'EQ',
            value: 1
          }
        ]
      }
      this.allBusiTypeKeyValue = {}
      wfBusiTypeSelect(queryArgs).then(res => {
        this.allBusiTypeList = res.data.data.records
        // for (var i = 0; i < 20; i++) {
        //   this.allBusiTypeList.push({
        //     busiTypeId: res.data.data.records[0].busiTypeId + i,
        //     busiTypeName: res.data.data.records[0].busiTypeName + i
        //   })
        // }
        // console.log('this.allBusiTypeList', this.allBusiTypeList)
        if (this.allBusiTypeList && this.allBusiTypeList.length > 0) {
          this.allBusiTypeKeyValue = this.allBusiTypeList.reduce((acc, cur) => {
            acc[cur.busiTypeId] = cur.busiTypeName
            return acc
          }, {})
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    fetchData() {
      this.checkBusiTypeList = []
      queryRecord(this.record.id).then(res => {
        this.loading = false
        this.record = res.data.data
        if (this.record && this.record.busiTypeList) {
          this.record.busiTypeList.forEach((item, index) => {
            if (item) {
              this.checkBusiTypeList.push(item.busiTypeId)
            }
          })
        }
        console.log('this.checkBusiTypeList', this.checkBusiTypeList)
      }).catch((err) => {
        console.log(err)
      })
    },
    createSave(formName, type) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 验证授权业务
          if (this.record.isAllBusi === '1') {
            this.checkBusiTypeList = []
          } else {
            if (!this.checkBusiTypeList || this.checkBusiTypeList.length <= 0) {
              this.$message({
                type: 'error',
                message: '请选择授权的业务类型！'
              })
              return false
            }

            // 验证授权时间
            if (this.record.beginTime > this.record.endTime) {
              this.$message({
                type: 'error',
                message: '授权开始时间不能大于授权结束时间！'
              })
              return false
            }

            // 设置授权业务类型
            this.record.busiTypeList = []
            this.checkBusiTypeList.forEach((item, index) => {
              if (this.allBusiTypeKeyValue[item]) {
                this.record.busiTypeList.push({
                  busiTypeId: item,
                  busiTypeName: this.allBusiTypeKeyValue[item]
                })
              }
            })
          }
          // 验证授权单据所在公司
          if (this.record.isAllCorp !== '1' && !this.record.corpId) {
            this.$message({
              type: 'error',
              message: '请输入授权单据所在公司！'
            })
            return false
          }
          this.saveRecord(type)
        } else {
          this.$message({
            type: 'error',
            message: '数据验证失败!'
          })
          console.log('error validate!!')
          return false
        }
      })
    },
    saveRecord(type) {
      if (!this.record.id) {
        // this.record.formUserId = this.curUserId
        // this.record.formUserName = this.curOrgId

        console.log('recode', this.record)
        // 插入
        insertRecord(this.record).then(res => {
          this.saveCallBack(type, res)
        }).catch((err) => {
          console.log(err)
          this.saveErrorCallBack(type, err)
        })
      } else {
        console.log('recode', this.record)
        // 更新
        updateRecord(this.record.id, this.record).then(res => {
          this.saveCallBack(type, res)
        }).catch((err) => {
          console.log(err)
          this.saveErrorCallBack(type, err)
        })
      }
    },
    saveCallBack(type, res) {
      if (res.data && res.data.success) {
        this.$message({
          type: 'success',
          message: '保存成功!'
        })
        this.record = res.data.data
      } else {
        this.$message({
          type: 'error',
          message: '保存失败!' + res.data.message
        })
      }
    },
    saveErrorCallBack(type, err) {
      let msg = '服务器连接异常，保存失败!'
      this.$message({
        type: 'error',
        message: msg
      })
    },
    closeComponent() {
      try {
        this.$emit('closeComponent')
      } catch (e) {
        //
      }
    },
    toSelectFormUser() {
      this.selectFormUserDialog = true
    },
    toSelectUser() {
      this.selectUserDialog = true
    },
    closeSelectFormUser(type, args) {
      if (type === 'save' && args) {
        this.record.formUserId = args.userId
        this.record.formUserName = args.userName
      } else if (type === 'clear') {
        this.record.formUserId = ''
        this.record.formUserName = ''
      }
      this.selectFormUserDialog = false
    },
    closeSelectUser(type, args) {
      if (type === 'save' && args) {
        this.record.toUserId = args.userId
        this.record.toUserName = args.userName
      } else if (type === 'clear') {
        this.record.toUserId = ''
        this.record.toUserName = ''
      }
      this.selectUserDialog = false
    },
    toSelectCorp() {
      this.selectCorpDialog = true
    },
    closeSelectCorp(type, args) {
      //
      if (type === 'save' && args) {
        this.record.busiCorpId = args.corpId
        this.record.busiCorpName = args.corpName
      } else if (type === 'clear') {
        this.record.busiCorpId = ''
        this.record.busiCorpName = ''
      }
      this.selectCorpDialog = false
    }
  }
}
</script>
<style scoped>
  .menu-navbar{
    padding:0 0 20px;
    text-align: right;
  }
  .container{
    padding: 0 10px;
    height: 100%;
    overflow-x: hidden;
    overflow-y: auto;
  }
  .myWidth{
    width: 70% !important;
  }
</style>
